import string
from random import choice

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from rest_framework import status
from rest_framework import viewsets
from rest_framework import mixins
from rest_framework.response import Response
from django.db.models import Q

from users.models import EmailVerifyCode
from users.serializers import VerifyCodeSerializer

User = get_user_model()


class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class UserViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    """
    发送邮箱验证码
    """
    queryset = EmailVerifyCode.objects.all()
    serializer_class = VerifyCodeSerializer

    def generate_code(self):
        verify_string = string.ascii_letters + string.digits
        code = []
        for x in range(4):
            code.append(choice(verify_string))
        return "".join(code)


    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 发送验证码 并保存至数据库
        email = serializer.validated_data['email']
        code = self.generate_code()
        re = send_mail("验证码", code, "hehecat@foxmail.com", [email], fail_silently=False)
        if re != 1:
            return Response({
                "email": 'error'
            }, status=status.HTTP_400_BAD_REQUEST)
        else:
            code_record = EmailVerifyCode(email=email, code=code)
            code_record.save()
            return Response({
                "email": email
            }, status=status.HTTP_201_CREATED)


